package com.hisan.freeride.home.activity;

import android.content.Intent;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.hisan.freeride.R;
import com.hisan.freeride.common.Dialog.CartDialogLogok;
import com.hisan.freeride.common.Dialog.CartDialogLogout;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.event.DataSynEvent;
import com.hisan.freeride.common.listener.IEditTextChangeListener;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.CompressPhotoUtils;
import com.hisan.freeride.common.utils.GlideImageLoader;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.WorksSizeCheckUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.common.view.CustomDatePicker;
import com.hisan.freeride.databinding.CationBinding;
import com.hisan.freeride.home.model.MyDriver;
import com.hisan.freeride.home.model.MyImageUrl;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.callback.ConfigButton;
import com.mylhyl.circledialog.callback.ConfigDialog;
import com.mylhyl.circledialog.params.ButtonParams;
import com.mylhyl.circledialog.params.DialogParams;
import com.ziyeyouhu.library.KeyboardTouchListener;
import com.ziyeyouhu.library.KeyboardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.qqtheme.framework.picker.CarNumberPicker;


/**
 * 创建时间 : 2017/6/12
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：车主认证页面
 */
public class CartCertificationActivity extends BaseActivity<CationBinding> {
    //驾驶证默认图片集合
    private ArrayList<ImageItem> imageItems1;
    //行驶证正面图片集合
    private ArrayList<ImageItem> imageItems2;
    private Intent intent;
    //驾驶证、行驶证照片
    private String avatar, avatar2 ;
    //车牌弹窗
    private CarNumberPicker picker;
    //上传内容
    private String fconnet;
    private String cart_name;
    private String linkname;
    private String drivename;
    private String year;
    private String hold;
    private KeyboardUtil keyboardUtil;
    private CustomDatePicker datePicker;
    private String time;
    private String date;
    //用户识别照片顺序
    private int type=0;

    @Override
    protected int getLayoutId() {
        return R.layout.cation;
    }

    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        EventBus.getDefault().register(this);
        keyboardUtil = new KeyboardUtil(this, mBinding.rootView, mBinding.svMain);;
        keyboardUtil.setKeyBoardStateChangeListener(new KeyBoardStateListener());
        keyboardUtil.setInputOverListener(new inputOverListener());
        mBinding.frienddetailsConnet.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_ABC , -1));
        mBinding.driveName.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_X , -1));
        keyboardUtil.setOtherEdittext(mBinding.linkname);
        keyboardUtil.setOtherEdittext(mBinding.hold);
        imageItems1=new ArrayList<>();
        imageItems2=new ArrayList<>();
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(1);    //最多选择1张
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        picker = new CarNumberPicker(this);
        picker.setOffset(3);
        mBinding.welfare.setEnabled(false);
        //1.创建工具类对象 把要改变颜色的Button先传过去
        WorksSizeCheckUtil.textChangeListener textChangeListener = new WorksSizeCheckUtil.textChangeListener(mBinding.welfare);
        //2.把所有要监听的edittext都添加进去
        textChangeListener.addAllEditText(mBinding.frienddetailsConnet,mBinding.linkname,mBinding.linkname,mBinding.hold);
        //3.接口回调 在这里拿到boolean变量 根据isHasContent的值决定 tv 应该设置什么颜色
        WorksSizeCheckUtil.setChangeListener(new IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                if(isHasContent){
                    mBinding.welfare.setEnabled(true);
                }else{
                    mBinding.welfare.setEnabled(false);
                }
            }
            @Override
            public void afterChange(Editable editable) {}
        });
    }

    @Override
    protected void initEvent() {
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        picker.setOnWheelLinkageListener((firstIndex, secondIndex, thirdIndex) -> mBinding.cartName.setText(picker.getSelectedFirstItem().getName()+""+picker.getSelectedSecondItem().getName()));
        mBinding.identitySelect.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(imageItems1)){
                keyboardUtil.hideKeyboardLayout();
                type=0;
                getmDialog("是否替换当前身份证照片？","取消","确定").show();
            }else{
                toImage(0);
            }
        });
        mBinding.identitySelect2.setOnClickListener(v -> {
            keyboardUtil.hideKeyboardLayout();
            if (!CollectionUtils.isNullOrEmpty(imageItems2)){
                type=1;
                getmDialog("是否替换当前身份证照片？","取消","确定").show();
            }else{
                toImage(1);
            }
        });
        mBinding.cart.setOnClickListener(v -> picker.show());
        mBinding.selectTime.setOnClickListener(v -> {
            keyboardUtil.hideKeyboardLayout();
            showDatePickDialog();
        });
        //提交审核
        mBinding.welfare.setOnClickListener(v -> {
            //车牌号
            fconnet= mBinding.frienddetailsConnet.getText().toString();
            cart_name=mBinding.cartName.getText().toString();
            linkname= mBinding.linkname.getText().toString();
            drivename= mBinding.driveName.getText().toString();
            year=mBinding.yearName.getText().toString();
            hold=mBinding.hold.getText().toString();
            if (CollectionUtils.isNullOrEmpty(cart_name)||CollectionUtils.isNullOrEmpty(fconnet)||CollectionUtils.isNullOrEmpty(linkname)
                    ||CollectionUtils.isNullOrEmpty(drivename)||CollectionUtils.isNullOrEmpty(year) ||CollectionUtils.isNullOrEmpty(avatar)
                    ||CollectionUtils.isNullOrEmpty(avatar2)){
                showToast("请输入完整信息.....");
                return;
            }
            CartDialogLogout.getInstance().show(getSupportFragmentManager(), "CartDialogLogout");
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.get(AppConfig.Getmydriver)
                .tag(this)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                showData();
                                if (isNull(response)){
                                    String data=GsonUtils.GsonString(response.body());
                                    MyDriver mydriver= GsonUtils.GsonToBean(data,MyDriver.class);
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getCar_no())){
                                        String car_no= mydriver.getCar_no().substring(0,2);
                                        mBinding.cartName.setText(car_no);
                                        String frienddetails=mydriver.getCar_no().substring(2,mydriver.getCar_no().length());
                                        mBinding.frienddetailsConnet.setText(frienddetails);
                                    }
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getRealname()))
                                        mBinding.linkname.setText(mydriver.getRealname());
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getDriver_license_no()))
                                        mBinding.driveName.setText(mydriver.getDriver_license_no());
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getDriver_license_get_time()))
                                        mBinding.yearName.setText(mydriver.getDriver_license_get_time()+"");
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getVehicle_owner()))
                                        mBinding.hold.setText(mydriver.getVehicle_owner());
                                    if (!CollectionUtils.isNullOrEmpty(mydriver.getDriver_license_photo()))
                                        avatar = mydriver.getDriver_license_photo();
                                    if (!CollectionUtils.isNullOrEmpty(avatar)) {
                                        Glide.with(CartCertificationActivity.this)
                                                .load(avatar)
                                                .placeholder(R.mipmap.realname)//设置占位图
                                                .error(R.mipmap.realname)
                                                .into(mBinding.driveIamgeBig);
                                        mBinding.driveIamge.setVisibility(View.GONE);
                                        mBinding.driveText.setVisibility(View.GONE);
                                        mBinding.driveIamgeBig.setVisibility(View.VISIBLE);
                                    }
                                    avatar2 =mydriver.getDriver_license_photo();
                                    if (!CollectionUtils.isNullOrEmpty(avatar2)) {
                                        Glide.with(CartCertificationActivity.this)
                                                .load(avatar2)
                                                .placeholder(R.mipmap.realname)//设置占位图
                                                .error(R.mipmap.realname)
                                                .into(mBinding.drivingIamgeBig);
                                        mBinding.drivingIamge.setVisibility(View.GONE);
                                        mBinding.drivingText.setVisibility(View.GONE);
                                        mBinding.drivingIamgeBig.setVisibility(View.VISIBLE);
                                    }
                                    String  msg="";
                                    if (mydriver.getReview()==0){
                                        msg="审核中";
                                        showToast(msg);
                                    }else if (mydriver.getReview()==2){
                                        msg="审核被拒绝";
                                        showToast(msg);
                                    }
                                }


                            } else {
                                showError(response);
                            }
                        }else {
                            noData();
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    //选择日期
    private void showDatePickDialog() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        time = sdf.format(new Date());
        date = time.split(" ")[0];
        /**
         * 设置年月日
         */
        datePicker = new CustomDatePicker(this, "请选择您的驾驶证初次领证时间", time1 -> mBinding.yearName.setText(time1.split(" ")[0]), "1007-01-01 00:00", time);
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);
        datePicker.show(date);
    }


    private void toImage(final int type) {
        //0：上传身份证正面照 1：上传手持身份证
        final String[] items = {"相册", "相机"};
        new CircleDialog.Builder(this)
                .configDialog(new ConfigDialog() {
                    @Override
                    public void onConfig(DialogParams params) {
                    }
                })
                .setTitle("选择照片")
                .setTitleColor(getResources().getColor(R.color.home_titel))
                .setItems(items, (parent, view, position, id) -> {
                    if (!CollectionUtils.isNullOrEmpty(items)){
                        if (items[position].equals("相册")){
                            Intent intent1 = new Intent(CartCertificationActivity.this,ImageGridActivity.class);
                            if (type==0){
                                startActivityForResult(intent1, 100);
                            }else{
                                startActivityForResult(intent1, 99);
                            }
                        }else{
                            Intent intent1 = new Intent(CartCertificationActivity.this,ImageGridActivity.class);
                            intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); //
                            if (type==0){
                                startActivityForResult(intent1, 100);
                            }else{
                                startActivityForResult(intent1, 99);
                            }
                        }
                    }
                })
                .setNegative("取消", null)
                .configNegative(new ConfigButton() {
                    @Override
                    public void onConfig(ButtonParams params) {
                        //取消按钮字体颜色
                        params.textColor = getResources().getColor(R.color.home_titel);
                    }
                })
                .show();
    }

    @Override
    public void onOk() {
        super.onOk();
        toImage(type);
    }

    @Override
    public void onCancel() {
        super.onCancel();
        if (mDialog.isShowing())mDialog.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(DataSynEvent event) {
        if (event.getid()==0){

            Saverealname(cart_name+""+fconnet,linkname,drivename,year,avatar,hold,avatar2);
        }else {
            finishActivity(true);
            showToast("车主认证成功,请等待后台审核");
        }
    }

    //创建车主认证
    private void Saverealname(String fconnet, String name, String drivename,String year, String avatar,String hold, String avatar2){
        HttpParams params=new HttpParams();
        params.put("city_id", BaseAppLication.getInstance().getCityid());

        params.put("realname",name);
        params.put("car_no",fconnet);
        params.put("driver_license_no",drivename);
        params.put("vehicle_owner",hold);
        params.put("car_no",fconnet);
        params.put("driver_license_get_time",year);
        params.put("driver_license_photo",avatar);
        params.put("driving_license_photo",avatar2);
        LogUtils.v("xxx",params.toString());
        OkGo.put(AppConfig.Savedriver)
                .tag(this)
                .params(params)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)){
                            if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                            setResult(99,intent);
                            CartDialogLogok.getInstance().show(getSupportFragmentManager(), "CartDialogLogok");
                        }else {
                            showError(response);
                        }

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                imageItems1 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems1 != null && imageItems1.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems1.size(); i++) {
                        if (i == imageItems1.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems1.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems1.get(i).path).append("\n");
                    }
                    formUpload();
                } else {
                    showToast("没有选择图片");
                }
            }else{
                imageItems2 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems2 != null && imageItems2.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems2.size(); i++) {
                        if (i == imageItems2.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems2.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems2.get(i).path).append("\n");
                    }
                    formUpload2();
                } else {
                    showToast("没有选择图片");
                }
            }
        }
    }

    //上传图片
    private  void formUpload(){
        ArrayList<File> files = new ArrayList<>();
        if (!CollectionUtils.isNullOrEmpty(imageItems1)) {
            new CompressPhotoUtils().CompressPhoto(CartCertificationActivity.this, imageItems1, new CompressPhotoUtils.CompressCallBack() {
                @Override
                public void success(List<String> list) {
                    if (list.size()>0) {
                        for (int i = 0; i < list.size(); i++) {
                            files.add(new File(list.get(i)));
                        }
                        OkGo.post(AppConfig.UpLoad)
                                .tag(this)
                                .addFileParams("image", files)
                                .execute(new DialogCallback<Object>(CartCertificationActivity.this) {
                                    @Override
                                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                                        super.onSuccess(response);
                                        if (!CollectionUtils.isNullOrEmpty(response)) {
                                            if (isOk(response)) {
                                                try {
                                                    String data= GsonUtils.GsonString(response.body());
                                                    MyImageUrl json = GsonUtils.GsonToBean(data,MyImageUrl.class);
                                                    avatar = json.getFile();

                                                    if (!CollectionUtils.isNullOrEmpty(avatar)) {
                                                        Glide.with(CartCertificationActivity.this)
                                                                .load(avatar)
                                                                .placeholder(R.mipmap.realname)//设置占位图
                                                                .error(R.mipmap.realname)
                                                                .into(mBinding.driveIamgeBig);
                                                        mBinding.driveIamge.setVisibility(View.GONE);
                                                        mBinding.driveText.setVisibility(View.GONE);
                                                        mBinding.driveIamgeBig.setVisibility(View.VISIBLE);
                                                    }
                                            } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        } else {
                                            showError(response);
                                        }
                                    }

                                    @Override
                                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                                        super.onError(response);
                                        showError(response);
                                    }
                                });
                    }
                }
            });
            }
    }

    //上传图片
    private  void formUpload2(){
        ArrayList<File> files = new ArrayList<>();
        if (!CollectionUtils.isNullOrEmpty(imageItems2)) {
            new CompressPhotoUtils().CompressPhoto(CartCertificationActivity.this, imageItems2, new CompressPhotoUtils.CompressCallBack() {
                @Override
                public void success(List<String> list) {
                    if (list.size()>0){
                        for (int i = 0; i < list.size(); i++) {
                            files.add(new File(list.get(i)));
                        }
                        OkGo.post(AppConfig.UpLoad)
                                .tag(this)
                                .addFileParams("image", files)
                                .execute(new DialogCallback<Object>(CartCertificationActivity.this){
                                    @Override
                                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                                        super.onSuccess(response);
                                        if (!CollectionUtils.isNullOrEmpty(response)) {
                                            if (isOk(response)){
                                                try {
                                                    String data= GsonUtils.GsonString(response.body());
                                                    MyImageUrl json = GsonUtils.GsonToBean(data,MyImageUrl.class);
                                                    avatar2 = json.getFile();

                                                    if (!CollectionUtils.isNullOrEmpty(avatar2)) {
                                                        Glide.with(CartCertificationActivity.this)
                                                                .load(avatar2)
                                                                .placeholder(R.mipmap.realname)//设置占位图
                                                                .error(R.mipmap.realname)
                                                                .into(mBinding.drivingIamgeBig);
                                                        mBinding.drivingIamge.setVisibility(View.GONE);
                                                        mBinding.drivingText.setVisibility(View.GONE);
                                                        mBinding.drivingIamgeBig.setVisibility(View.VISIBLE);
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();}
                                            }
                                        }else {
                                            showError(response);
                                        }
                                    }

                                    @Override
                                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                                        super.onError(response);
                                        showError(response);
                                    }
                                });
                    }
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //自定义键盘监听物理返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) {
            if(keyboardUtil.isShow){
                keyboardUtil.hideSystemKeyBoard();
                keyboardUtil.hideAllKeyBoard();
                keyboardUtil.hideKeyboardLayout();
            }else {
                return super.onKeyDown(keyCode, event);
            }

            return false;
        } else
            return super.onKeyDown(keyCode, event);
    }
    class KeyBoardStateListener implements KeyboardUtil.KeyBoardStateChangeListener {
        @Override
        public void KeyBoardStateChange(int state, EditText editText) {}}

    class inputOverListener implements KeyboardUtil.InputFinishListener {

        @Override
        public void inputHasOver(int onclickType, EditText editText) {}}
}
